package com.formula.distribution.limit.utils;

import com.formula.distribution.limit.enums.RateLimitConstantEnums;
import com.formula.distribution.limit.enums.RateLimitTypeEnum;
import com.formula.distribution.limit.exception.RateLimitException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * @author:bo
 * @email:
 * @date 2018/12/13 14:53
 * @introduce
 **/
public class RateLimitUtils {


    /**
     * 获取
     *
     * @param joinPoint
     * @param rateLimitTypeEnum
     * @return
     */
    public static String getRateKey(JoinPoint joinPoint, RateLimitTypeEnum rateLimitTypeEnum) {

        StringBuffer key = new StringBuffer(RateLimitConstantEnums.HASH_TAG);

        // 以方法名加参数列表作为key
        if (RateLimitTypeEnum.ALL.equals(rateLimitTypeEnum)) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

            key.append(methodSignature.getMethod().getName());
            Class[] parameterTypes = methodSignature.getParameterTypes();
            Arrays.stream(parameterTypes).forEach(parameter -> {
                key.append(parameter.getName());
            });
            key.append(joinPoint.getTarget().getClass());
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();
        //  以ip 作为key

        if (RateLimitTypeEnum.IP.equals(rateLimitTypeEnum)) {
            key.append(getIpAddr(request));
        }
        // 以自定义作为key
        if (RateLimitTypeEnum.CUSTOM.equals(rateLimitTypeEnum)) {
            if (null != request.getAttribute(RateLimitConstantEnums.CUSTOM)) {

                key.append(request.getAttribute(RateLimitConstantEnums.CUSTOM).toString());
            } else {
                throw new RateLimitException("not found custom info ,please check request.getAttribute('syj-rateLimit-custom')!!!");
            }
        }
        return key.toString();
    }


    /**
     * 获取当前网络ip
     *
     * @param request HttpServletRequest
     * @return ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
